/**
 * 文字裁剪
 * @param {*} str
 * @param {*} len
 */
export const textClip = (str = '', len = 10) => {
  if (typeof str === 'string' && typeof len === 'number' && len > 1) {
    if (str.length <= len) {
      return str
    } else {
      return `${str.substring(0, len)}…`
    }
  } else {
    console.error('Parameter is error！')
  }
}

/**
 * 图片地址格式化过滤器
 */
export const transformImgUrl = (val) => {
  if (!val) return
  if (val.indexOf('http') === -1 && val.indexOf('Upload') === -1 && val.indexOf('base64') === -1) {
    return `${process.env.IMAGE_HOST}/File/GetImage/${val}`
  } else {
    // 值为完整url
    return val
  }
}

/**
 * 时间格式化
 * @param {*} date
 * @param {*} fmt
 */
export const formatDateTime = (date, fmt = 'YYYY-MM-DD HH:mm:ss') => {
  date = new Date(date)
  if (isNaN(date.getTime())) {
    return '-'
  }
  var o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  var week = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  }
  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

/**
 * 金额格式化
 * @param {*} amount 金额
 * @param {*} unit 符号
 */
export const currencyFormat = (amount = 0, {unit = '', Places = 2}) => {
  amount = parseFloat(amount)
  amount = amount.toFixed(Places)
  amount = `${amount}`
  amount = amount.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
  return `${unit}${amount}`
}

/**
 * 字符串脱敏
 */
export const strHide = {
  mobile (mobile) { // 手机
    return mobile ? mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2') : '-'
  },
  bankCard (bankCardCode) { // 手机
    return bankCardCode ? bankCardCode.replace(/(\d{5})\d*(\d{4})/, '$1*********$2') : '-'
  }
}
